To Obtain EPOCH Time Value from a Packed BIT Structure in C [migrated]

Posted by xde0037 on Programmers See other posts from Programmers or by xde0037
Published on 2012-03-29T14:13:01Z Indexed on 2012/03/29 17:41 UTC
Read the original article Hit count: 180

Filed under:

This is not a home assignment! We have a binary data file which has following data structure: (It is a 12 byte structure): I need to find out Epoch time value(total time value is packed in 42 bits as described below):

Field-1 : Byte 1, Byte 2, + 6 Bits from Byte 3
Time-1  :                   2 Bits from Byte 3 + Byte 4
Time-2  : Byte 5, Byte 6, Byte 7, Byte 8
Field-2 : Byte 9, Byte 10, Byte 11, Byte 12
For Field-1 and Field-2 I do not have issue as they can be taken out easily. 
I need time value in Epoch Time (long) as it has been packed in 
Bytes 5,6,7,8 and 3 and 4 as follows:
(the bit structure for the time value is as follows):
Bytes 5 to 8 (32 bit word) Packs time value bits 
from 0 thru 31 (byte 5 has 0 to 7 bits,
     byte 6 has 8 to 15, byte 7 has 16 to 23, byte 8 has 24 to 31).
the remaining 10 bits of time value are packed in Bytes 3 and byte 4 as follows:
     byte 3 has 2 bits:32 and 33, and Byte 4 has remaining bits : 34 to 41.
So total bits for time value is 42 bits, packed as above.
I need to compute epoch value coming out of these 42 bits. How do I do it?
I have done something like this but not sure it gives me correct value:
typedef struct P_HEADER {
    unsigned int tmuNumber : 21; 
    unsigned int time1 : 10; // Bits 6,7 from Byte-3 + 8 bits from Byte-4
    unsigned int time2 : 32; // 32 bits: Bytes 5,6,7,8
    unsigned int traceKey : 32; 
} __attribute__((__packed__)) P_HEADER;

Then in the code :

P_HEADER *header1;

//get input string in hexa,etc..etc..
//parse the input with the header as :
header1 = (P_HEADER *)inputBuf;
// then print the header1->time1, header1->time2 ....
long ttime = header1->time1|header1->time2;  //?? is this the way to get values out?

Any hint tip will be appreciated. Environment is : gcc 4.1, Linux Thanks in advance.

© Programmers or respective owner

Related posts about c